import socket
import json


class ClientSocket:
    def __init__(self, host='localhost', port=12345):
        self.host = host
        self.port = port
        self.socket = None

    def connect(self):
        """连接到服务器"""
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.connect((self.host, self.port))
            return True
        except Exception as e:
            print(f"连接服务器失败: {e}")
            return False

    def send_data(self, data):
        """发送数据到服务器"""
        if not self.socket:
            if not self.connect():
                return False

        try:
            # 假设数据是字典，转换为JSON字符串发送
            json_data = json.dumps(data) + '\n'
            self.socket.sendall(json_data.encode('utf-8'))
            return True
        except Exception as e:
            print(f"发送数据失败: {e}")
            self.close()
            return False

    def receive_data(self):
        """从服务器接收数据"""
        if not self.socket:
            return None

        try:
            data = self.socket.recv(4096).decode('utf-8')
            if data:
                return json.loads(data)
            return None
        except Exception as e:
            print(f"接收数据失败: {e}")
            self.close()
            return None

    def close(self):
        """关闭连接"""
        if self.socket:
            self.socket.close()
            self.socket = None